package com.linln.admin.system.controller;

import com.linln.common.exception.ResultException;
import com.linln.common.utils.HttpServletUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.common.vo.WangEditor;
import com.linln.component.fileUpload.FileUpload;
import com.linln.component.fileUpload.enums.UploadResultEnum;
import com.linln.modules.system.domain.Upload;
import com.linln.modules.system.service.UploadService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 小懒虫
 * @date 2018/11/02
 */
@Slf4j
@Controller
public class UploadController {

	@Autowired
	private UploadService uploadService;

	/**
	 * 上传web格式图片
	 */
	@PostMapping("/upload/image")
	@ResponseBody
	public ResultVo uploadImage(@RequestParam("image") MultipartFile multipartFile) {

		// 创建Upload实体对象
		Upload upload = FileUpload.getFile(multipartFile, "/images");
		try {
			return saveImage(multipartFile, upload);
		} catch (IOException | NoSuchAlgorithmException e) {
			return ResultVoUtil.error("上传图片失败");
		}
	}

	@ApiOperation("图片读取")
	@GetMapping(value = "/upload/{module}/{date}/{fileName}")
	public void image(@PathVariable String module, @PathVariable String date, @PathVariable String fileName, HttpServletResponse response) throws IOException {
		OutputStream os = null;
		final String path = module + "/" + date + "/" + fileName;
		try {
			BufferedImage image = ImageIO.read(new FileInputStream(new File(FileUpload.getUploadPath() + path)));
			response.setContentType("image/png");
			os = response.getOutputStream();
			if (image != null) {
				ImageIO.write(image, "png", os);
			}
		} catch (Exception e) {
			log.error("获取图片异常{},请求参数{}", e.getMessage(), path);
		} finally {
			if (os != null) {
				os.flush();
				os.close();
			}
		}

	}

	/**
	 * 上传layui富文本编辑器组件的图片
	 */
	@PostMapping("/upload/wang/image")
	@ResponseBody
	public WangEditor uploadLayImage(@RequestParam("file") MultipartFile multipartFile) {

		// 创建Upload实体对象
		Upload upload = FileUpload.getFile(multipartFile, "/images");
		try {
			final ResultVo<Upload> uploadResultVo = saveImage(multipartFile, upload);
			String[] strs = {HttpServletUtil.getBaseUrl() + upload.getPath()};

			WangEditor we = new WangEditor(strs);

			return we;
		} catch (IOException | NoSuchAlgorithmException e) {
			log.error("上传文件失败", e);
		}
		return null;

	}


	/**
	 * 上传web格式头像
	 */
	@PostMapping("/upload/picture")
	@ResponseBody
	public ResultVo uploadPicture(@RequestParam("picture") MultipartFile multipartFile) {

		// 创建Upload实体对象
		Upload upload = FileUpload.getFile(multipartFile, "/picture");
		try {
			return saveImage(multipartFile, upload);
		} catch (IOException | NoSuchAlgorithmException e) {
			return ResultVoUtil.error("上传头像失败");
		}
	}

	/**
	 * 保存上传的web格式图片
	 */
	private ResultVo<Upload> saveImage(MultipartFile multipartFile, Upload upload) throws IOException, NoSuchAlgorithmException {
		// 判断是否为支持的图片格式
		String[] types = {
				"image/gif",
				"image/jpg",
				"image/jpeg",
				"image/png"
		};
		if (!FileUpload.isContentType(multipartFile, types)) {
			throw new ResultException(UploadResultEnum.NO_FILE_TYPE);
		}

		// 判断图片是否存在
		Upload uploadSha1 = uploadService.getBySha1(FileUpload.getFileSha1(multipartFile));
		if (uploadSha1 != null) {
			return ResultVoUtil.success(uploadSha1);
		}

		FileUpload.transferTo(multipartFile, upload);
		// 将文件信息保存到数据库中
		upload.setPath(upload.getPath());
//		upload.setPath(HttpServletUtil.getBaseUrl()+upload.getPath());
		uploadService.save(upload);
		return ResultVoUtil.success(upload);
	}

}
